// pages/topic_creat/topic_creat.js
import { request } from "../../request/index.js";
import { showModal, showToast, uploadFile, chooseImage, showLoading } from "../../util/AsyncWx.js";
var app = getApp();
let a = ''

Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],
    checked: '',
    tabs: [
      {
        id: 0,
        value: "发布贴子",
        isActive: true
      },
      {
        id: 1,
        value: "发布商品",
        isActive: false
      },
    ],
    currentIndex: 0,
    contentLength: '',
    descriptionLength: '',
    //被选中的图片路径数组
    chooseImgs1: [],
    chooseImgs2: [],
    content: '',
    description: '',
    price: '',
    contact: '',
    imgurl: '',
    goods: {
      description: '',
      price: '',
      contact: '',
      userid: '',
      imgurl: '',
    },
    topic: {
      content: '',
      cid: '',
      uid: '',
      imgurl: '',
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  async onShow() {
    if (a) {
      a = false;
      return
    } else {
      // wx.request({
      //   url: 'http://192.168.0.108:8080/category/getCategoryAll',
      //   header: {'content-type':'application/json'},
      //   method: 'GET',
      //   dataType: 'json',
      //   responseType: 'text',
      //   success: (result)=>{
      //     this.setData({
      //       categoryList:result.data
      //     })
      //   },
      //   fail: ()=>{},
      //   complete: ()=>{}
      // });
      const result = await request({ url: "/category/getCategoryAllName" })
      this.setData({
        categoryList: result,
        contentLength: 0,
        descriptionLength: 0,
      })
    }


  },
  ItemChange(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      currentIndex: index,
    })
  },
  radioChange: function (e) {
    var cid = 'topic.cid'
    this.setData({
      [cid]: e.detail.value
    })
  },
  handletabsItemChange(e) {
    //1.获取被点击的标题索引
    const { index } = e.detail;
    // 2修改原数组
    let { tabs } = this.data;
    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    //赋值到data中
    this.setData({
      tabs
    })
  },
  //发帖页面点击“+”选择图片事件
  async handleChooseImg1() {
    a = true
    //调用小程序内置的选择图片api
    if (this.data.chooseImgs1.length < 1) {
      const result = await chooseImage({});
      this.setData({
        chooseImgs1: result
      })
    } else {
      showToast({ title: "只能上传一张照片" })
    }

  },
  async handleChooseImg2() {
    a = true
    //调用小程序内置的选择图片api
    if (this.data.chooseImgs2.length < 1) {
      const result = await chooseImage({});
      this.setData({
        chooseImgs2: result
      })
    } else {
      showToast({ title: "只能上传一张照片" })
    }

  },
  handleRemoveImg1(e) {
    //获取被点击组件的索引
    const { index } = e.currentTarget.dataset;
    // 获取data中的图片数组
    let { chooseImgs1 } = this.data
    // 删除元素
    chooseImgs1.splice(index, 1);
    this.setData({
      chooseImgs1
    })

  },
  handleRemoveImg2(e) {
    //获取被点击组件的索引
    const { index } = e.currentTarget.dataset;
    // 获取data中的图片数组
    let { chooseImgs2 } = this.data
    // 删除元素
    chooseImgs2.splice(index, 1);
    this.setData({
      chooseImgs2
    })

  },
  handleImagePreview1(e) {
    a = true
    const idx = e.target.dataset.idx
    const images = this.data.chooseImgs1
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },
  handleImagePreview2(e) {
    a = true
    const idx = e.target.dataset.idx
    const images = this.data.chooseImgs2
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },

  contentInput: function (e) {
    var that = this
    var content = 'topic.content'
    var uid = 'topic.uid'
    var contentLength = that.data.topic.uid
    that.setData({
      [content]: e.detail.value,
      [uid]: app.globalData.uid,
      contentLength: e.detail.value.length
    })
  },
  descriptionInput: function (e) {
    var description = 'goods.description';
    var userid = 'goods.userid'
    this.setData({
      [description]: e.detail.value,
      [userid]: app.globalData.uid,
      descriptionLength: e.detail.value.length
    })
  },
  priceInput: function (e) {
    var price = 'goods.price'
    this.setData({
      [price]: e.detail.value
    })
  },
  contactInput: function (e) {
    var contact = 'goods.contact'
    this.setData({
      [contact]: e.detail.value
    })
  },
  async submit_topic() {
    var that = this
    var content = that.data.topic.content
    var cid = that.data.topic.cid
    var contentLength = that.data.contentLength
    if (content === '') {
      showToast({ title: "内容不能为空" })
      return false;
    } else if (cid === '') {
      showToast({ title: "请选择类别" })
      return false;
    } else if (contentLength > 255) {
      showToast({ title: "超出字数，最多写255个字" })
      return false;
    } else {
      const res = await showModal({ content: "确认发布吗？" });
      if (res.confirm) {
        that.addTopic()
      }
    }
  },
  async addTopic() {
    var that = this
    var topic = that.data.topic
    var imgurl = 'topic.imgurl'
    var url = that.data.chooseImgs1[0];
    if (url != null) {
      const res1 = await uploadFile({ url: "/imageUpload", filePath: url })
      that.setData({
        [imgurl]: res1.data
      })
    }
    showLoading({ title: "发布中..." })
    const res2 = await request({ url: "/topic/addTopic", method: "POST", data: topic })
    wx.hideLoading();
    if (res2 === "ok") {
      showToast({ title: "发布成功" });
      that.setData({
        chooseImgs1: [],
        topic: {
          content: '',
          cid: '',
          uid: '',
          imgurl: ''
        },
        checked: false
      })
    }
    else {
      showToast({ title: "发布失败" });
    }
  },
  isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
      return true;
    } else {
      return false;
    }
  },
  async formSubmit(e) {
    var that = this;
    var description = e.detail.value.description
    var price = e.detail.value.price
    var contact = e.detail.value.contact
    var descriptionLength = that.data.descriptionLength
    if (description == '') {
      showToast({ title: "商品描述不能为空" })
      return false;
    } else if (price == '') {
      showToast({ title: "商品价格不能为空" })
      return false;
    } else if (descriptionLength > 255) {
      showToast({ title: "超出字数限制" })
      return false;
    } else if (contact == '') {
      showToast({ title: "微信号不能为空" })
      return false;
    } else if (that.isNumber(price) === false) {
      showToast({ title: "请正确输入价格" })
      return false
    } else if (that.data.chooseImgs2.length === 0) {
      showToast({ title: "图片不能为空" })
    } else {
      const res = await showModal({ content: "确认发布商品吗？" })
      if (res.confirm) {
        that.addGoods()
      }
    }

  },
  async addGoods() {
    var that = this
    var goods = that.data.goods
    var imgurl = 'goods.imgurl'
    var url = that.data.chooseImgs2[0];
    const res = await uploadFile({ url: "/imageUpload", filePath: url })
    that.setData({
      [imgurl]: res.data

    })
    showLoading({ title: "发布中..." })
    const res2 = await request({ url: "/goods/addGood", method: "POST", data: goods })
    wx.hideLoading();
    if (res2 === "ok") {
      showToast({ title: "发布成功" })
    } else {
      showToast({ title: "发布失败" })
    }
    that.setData({
      chooseImgs2: [],
      goods: {}
    })
  },

})